package top.jlzhou;

import java.io.File;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import top.jlzhou.boot.tools.autoconfigure.PathProperties;

/**
 * <pre>
 * 路径
 * ClassName : top.jlzhou.Path
 * Author : J.L.Zhou
 * Date : 2019年3月20日 下午11:08:21
 * Version : V1.0
 * Copyright 2019 jlzhou.top Inc. All rights reserved. 
 * 注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目</pre>
 */
@Slf4j
public class Path {

	private PathProperties path;

	public Path(PathProperties path) {
		super();
		this.path = path;
	}


	/**
	 * 基本根路径，默认为jar所在路径，可以配置pepay.path.root
	 */
	@Getter
	private File root;

	/**
	 * 上传路径，默认为root路径下的upload目录,可以配置pepay.path.upload
	 */
	@Getter
	private File upload;

	
	/**
	 * <pre>根据传递的类，初始化默认位置</pre> 
	 * init
	 * @param cls      
	 * @throws	CodeException:
	 */
	public void init(Class<?> cls) {
		if (path.getRoot() != null && !"".equals(path.getRoot())) {
			root = new File(path.getRoot());
		} else {
			try {
				String path = cls.getProtectionDomain().getCodeSource().getLocation().getPath();
				path = java.net.URLDecoder.decode(path, "utf-8");
				if (path.indexOf("!") > -1) {
					path = path.substring(0, path.indexOf("!"));
				}
				if (path.endsWith(".jar")) {
					path = path.substring(0, path.lastIndexOf("/") + 1);
					if (path.startsWith("file:")) {
						path = path.substring(5);
					}
					root = new File(path);
				} else {
					root = new File(path).getParentFile();
				}
			} catch (Exception e) {
				log.warn("获取当前目录失败", e);
				root = new File("./").getAbsoluteFile();
			}
		}
		log.info("当前目录：{}", root);
		upload = new File(root, path.getUpload());
		log.info("文件上传目录：{}", upload);
	}
	
	/**
	 * <pre>根据Path.class，初始化默认位置</pre> 
	 * init      
	 * @throws	CodeException:
	 */
	public void init() {
		init(Path.class);
	}

}
